package com.example.stringbufferlogger.service;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.util.StringUtils;
import com.example.stringbufferlogger.Utils.JsonUtils;
import com.example.stringbufferlogger.dto.HttpRequest;
import com.example.stringbufferlogger.entity.LogRecord;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DwrRequestProcessor {

    private static final MediaType DWR_MEDIA_TYPE = MediaType.parse("text/plain");
    // DWR调用需要特殊处理，因为它是CometD长轮询协议

    public HttpRequest prepareDwrRequest(LogRecord record) {
        HttpRequest request = new HttpRequest();
        request.setUrl(convertDwrUrl(record.getUrl()));
        request.setMethod(record.getMethod());

        Map<String, String> headers = new HashMap<String, String>(convertToMap(record.getHeaders()));
        headers.put("Content-Type", "text/plain");
        request.setHeaders(headers);

        // 直接使用原始DWR请求体
        request.setBody(record.getRequestBody());

        return request;
    }

    private Map<String, String> parseDwrRequestBody(String body) {
        Map<String, String> params = new HashMap<>();
        if (StringUtils.isBlank(body)) {
            return params;
        }

        String[] pairs = body.split("&");
        for (String pair : pairs) {
            String[] kv = pair.split("=");
            if (kv.length == 2) {
                params.put(kv[0], URLDecoder.decode(kv[1], StandardCharsets.UTF_8));
            }
        }
        return params;
    }

    private String convertDwrRequestBody(Map<String, String> dwrParams) {
        // 实现DWR请求体到新系统格式的转换
        // 示例实现 - 根据实际情况调整
        JSONObject newBody = new JSONObject();
        newBody.put("callCount", dwrParams.get("callCount"));
        newBody.put("scriptSessionId", dwrParams.get("scriptSessionId"));
        newBody.put("c0-methodName", dwrParams.get("c0-methodName"));
        // 添加其他必要参数...

        return newBody.toString();
    }

    private String convertDwrUrl(String oldUrl) {
        // 转换DWR URL到新系统
        return oldUrl.replace("/dwr/call/plaincall/", "/api/dwr/");
    }

    private Map<String, ? extends String> convertToMap(String input) {
        if (input == null || input.isEmpty()) {
            return new HashMap<>();
        }
        try {
            // 尝试按JSON解析
            return JsonUtils.parseMap(input, String.class, String.class);
        } catch (Exception e1) {
            try {
                // 尝试按键值对解析
//                return parseKeyValueString(input, ",", ":");
            } catch (Exception e2) {
                log.error("Failed to parse input: {}", input, e2);
                return new HashMap<>();
            }
        }
        return null;
    }
}
